<template>
  <el-card class="common_card_wrapper">
    <el-button
      type="primary"
      icon="Plus"
      style="margin-bottom: 20px"
      @click="addTradeMark"
    >
      添加品牌
    </el-button>

    <el-table
      :data="tableData"
      :border="true"
      height="750px"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column prop="tmName" label="品牌名称" width="300" />
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template #default="{ row }">
          <img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="action" label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" icon="edit" @click="editRow(row)">
            编辑
          </el-button>
          <el-button type="danger" icon="delete" @click="deleteRow(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="common_pagination"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[30, 50, 100]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="total"
      @size-change="sizeChange"
      @current-change="getTrademark"
    />
    <!-- 弹窗组件 -->
    <Dialog
      :visible="diaologVisible"
      :dialogConfig="dialogConfig"
      @confirm="submitForm"
      @close="closeDialog"
    >
      <template #content>
        <el-form
          :model="form"
          label-width="auto"
          :rules="rules"
          ref="loginForm"
        >
          <el-form-item prop="tmName" label="品牌名称">
            <el-input v-model="form.tmName" placeholder="请输入品牌名称" />
          </el-form-item>
          <el-form-item prop="logoUrl" label="品牌LOGO">
            <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  reqTrademarkList,
  reqAddOrUpdateTrademark,
  delTrademark
} from '@/api/product/trademark'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Records, TrademarkResponseData } from '@/api/product/type'
import '@/styles/common/index.less'

onMounted(() => {
  getTrademark()
})

const currentPage = ref(1)
const pageSize = ref(30)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
let total = ref(0)
let tableData = reactive<Records>([])
let loading = ref(false)
let diaologVisible = ref(false)
let dialogConfig = reactive<any>({
  dialogTitle: '添加品牌',
  dialogWidth: '550px',
  dialogShowClose: true,
  dialogModal: true,
  dialogAlignCenter: false,
  dialogContentCenter: false,
  dialogClickModalClose: false,
  dialogESCModalClose: false,
  dialogDraggable: false,
  dialogFooterBtn: true,
  dialogFootConfirmBtnText: '确定',
  dialogFootCancelBtnText: '取消'
})
const form: any = reactive({
  tmName: '',
  logoUrl: ''
})
const rules = {
  tmName: [{ required: true, message: '品牌名称不能为空', trigger: 'blur' }],
  logoUrl: [
    {
      required: true,
      message: '品牌LOGO不能为空',
      trigger: 'blur'
    }
  ]
}
// 获取 form 实例
const loginForm = ref()

// 获取list列表
const getTrademark = async (pager = 1) => {
  currentPage.value = pager
  loading.value = true
  let res: TrademarkResponseData = await reqTrademarkList(
    currentPage.value,
    pageSize.value
  )
  if (res.code === 200) {
    tableData = res.data.records
    total.value = res.data.total
    loading.value = false
  } else {
    ElMessage.error(res.message)
    loading.value = false
  }
}
// 分页器 自定义条数方法
const sizeChange = () => {
  getTrademark()
}

// 新增品牌
const addTradeMark = () => {
  dialogConfig.dialogTitle = '添加品牌'
  form.id = ''
  diaologVisible.value = true
}

// 编辑
const editRow = (row: any) => {
  diaologVisible.value = true
  dialogConfig.dialogTitle = '编辑品牌'
  Object.assign(form, row)
}
// 删除
const deleteRow = (row: any) => {
  ElMessageBox.confirm(`确定删除${row.tmName}品牌吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteTrademarkMethod(row.id)
  })
}

// 新增or编辑方法
const onAddOrUpdateTrademarkMethod = async (id: any) => {
  let res: any = await reqAddOrUpdateTrademark(id)
  if (res.code === 200) {
    ElMessage.success(res.message)
    getTrademark(
      tableData.length > 1 ? currentPage.value : currentPage.value - 1
    )
    closeDialog()
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
}

// 删除方法
const deleteTrademarkMethod = async (id: any) => {
  let res: any = await delTrademark(id)
  if (res.code === 200) {
    ElMessage.success(res.message)
    getTrademark(currentPage.value)
  } else {
    ElMessage.error(res.data ? res.data : res.message)
  }
}

// 上传成功回调
const handleAvatarSuccess: any['onSuccess'] = (
  response: any,
  uploadFile: any
) => {
  ElMessage.success('上传成功')
  form.logoUrl = response.data
}

// 提交form
const submitForm = async () => {
  await loginForm.value.validate(async (valid: any) => {
    if (valid) {
      onAddOrUpdateTrademarkMethod(form)
    }
  })
}

// 关闭dialog
const closeDialog = () => {
  diaologVisible.value = false
  form.id = ''
  form.tmName = ''
  form.logoUrl = ''
  nextTick(() => {
    loginForm.value.resetFields()
  })
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
